import copy

LIST_Operator = ("+", "-", "*", "/","=")
LIST_Seperator = (";",)

class Quadruple:
    def __init__(self, op, arg1, arg2, result):
        self.op = op
        self.arg1 = arg1
        self.arg2 = arg2
        self.result = result

    def __str__(self):
        """
        返回表达式对象的字符串表示形式。
        
        Args:
            无
        
        Returns:
            str: 表达式对象的字符串表示形式，格式为"(op, arg1, arg2, result)"。
        
        """
        return f"({self.op}, {self.arg1}, {self.arg2}, {self.result})"

import re

Ccode = "if (x > 3){y = 4;}else{y = 6;}"

# 定义正则表达式模式
patterns = {
    'keyword': r'\b(if|else)\b',  # 关键字
    'identifier': r'\b([a-zA-Z_][a-zA-Z0-9_]*)\b',  # 标识符
    'integer': r'\b\d+\b',  # 整数
    'operator': r'[><=!]|-|\+|/|\*',  # 操作符
    'separator': r'[();{}]'  # 分隔符
}

# 合并所有模式为一个正则表达式
combined_pattern = '|'.join(f'(?P<{key}>{value})' for key, value in patterns.items())

# 使用正则表达式查找所有匹配的token
tokens = re.finditer(combined_pattern, Ccode)

# 打印识别的token
OutList = []
for token in tokens:
    print(token.group(0))
    OutList.append(token.group(0))

print("OutList", OutList)
    
def generate_quadruples(OutList):
    # 这里只是一个示例，实际的代码需要解析Python语法树
    # 并且生成对应的四元式
    quadruples = []
    index = 1
    for token in OutList:
        if token == 'if':
            #提取条件表达式
            CurIndex= OutList.index(token) 
            condition = ""
            while OutList[CurIndex] != '(': #找到(
                CurIndex += 1 
            CurIndex += 1 #跳过左括号
            while OutList[CurIndex] != ')':#找到)
                condition += OutList[CurIndex]
                CurIndex += 1
            #生成汇编跳转四元式，使用8086/8088的指令
            quadruples.append(Quadruple('CMP', condition, None, f"T{index}")) #比较
            index += 1
            quadruples.append(Quadruple('JZ', 'label-if-true', None, f"T{index}")) #相等
            index += 1
            quadruples.append(Quadruple('JMP', 'label-if-false', None, f"T{index}")) #无条件跳转
            index += 1
            exp = [] #表达式
            while OutList[CurIndex] != '{': #找到{
                CurIndex += 1 
            CurIndex += 1 #跳过左括号
            while OutList[CurIndex] != '}':#找到}
                exp.append(OutList[CurIndex])
                CurIndex += 1   
            operandStack = []
            operatorStack = []
            for i in range(len(exp)):
                if exp[i] not in LIST_Operator and exp[i] not in LIST_Seperator:
                    operandStack.append(exp[i])
                if exp[i]  in LIST_Operator :
                    operatorStack.append(exp[i])
            #生成四元式
            oprand2 = operandStack.pop()
            oprand1 = operandStack.pop()
            op = operatorStack.pop()
            quadruples.append(Quadruple(None, None, None, 'label-if-true'))
            quadruples.append(Quadruple(op, oprand1, oprand2, f"T{index}"))
            index += 1
            quadruples.append(Quadruple("JMP", 'next', None, f"T{index}"))
            index += 1
            # JZ 指令用于测试标志位 ZF（零标志位）。当 ZF = 1 时，即前面操作的结果为零，程序就会跳转到指定的偏移地址处执行。通常跟在一些能够影响 ZF 位的算术或逻辑运算指令之后。
        elif token == 'else':
            exp = [] #表达式
            while OutList[CurIndex] != '{': #找到{
                CurIndex += 1 
            CurIndex += 1 #跳过左括号
            while OutList[CurIndex] != '}':#找到}
                exp.append(OutList[CurIndex])
                CurIndex += 1   
            operandStack = []
            operatorStack = []
            for i in range(len(exp)):
                if exp[i] not in LIST_Operator and exp[i] not in LIST_Seperator:
                    operandStack.append(exp[i])
                if exp[i]  in LIST_Operator :
                    operatorStack.append(exp[i])
            #生成四元式
            oprand2 = operandStack.pop()
            oprand1 = operandStack.pop()
            op = operatorStack.pop()
            quadruples.append(Quadruple(None, None, None, 'label-if-false'))
            quadruples.append(Quadruple(op, oprand1, oprand2, f"T{index}"))
            index += 1
            quadruples.append(Quadruple(None, None, None, 'next'))
    return quadruples

# 生成四元式
quadruples = generate_quadruples(OutList)
for q in quadruples:
    print(q)